package com.shiguiwu.springmybatis.javabase.nio.socket;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.StandardCharsets;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * @description:
 * @author: stone
 * @date: Created by 2021/11/8 14:55
 * @version: 1.0.0
 * @pakeage: com.shiguiwu.springmybatis.nio.socket
 */
public class ServerSocketTests {

    public static void main(String[] args) throws Exception {

        //新建一个buffer
        ByteBuffer buffer = ByteBuffer.wrap("shiguiwu hello".getBytes(StandardCharsets.UTF_8));

        //创建serverSocket
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();

        //绑定端口
        serverSocketChannel.socket().bind(new InetSocketAddress(8000));

        //设置非阻塞模式
        serverSocketChannel.configureBlocking(false);

        //监听连接
        while (true) {
            System.out.println("Waiting for connections =================>");
            SocketChannel socketChannel = serverSocketChannel.accept();
            if (Objects.nonNull(socketChannel)) {

                System.out.println("Incoming connection from: " + socketChannel.socket().getRemoteSocketAddress());

                //设置指针为 0
                buffer.rewind();

                //写入buffer
                socketChannel.write(buffer);

                //关闭socket 连接
                socketChannel.close();

            }
            else {
                System.out.println("null ===> 没有连接上来");
                TimeUnit.SECONDS.sleep(2);

            }
        }
    }
}
